package com.jige.jigetodo.controller;

import com.google.code.kaptcha.Producer;
import com.jige.jigetodo.common.BaseResponse;
import com.jige.jigetodo.common.ResultUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("/verificationCode")
public class CaptchaController {

    @Resource
    private Producer kaptchaProducer;

    @GetMapping("/captcha")
    public BaseResponse<String> getCaptcha(HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        // 生成验证码文本
        String captchaText = kaptchaProducer.createText();
        session.setAttribute("captcha", captchaText);

        // 生成验证码图片
        BufferedImage captchaImage = kaptchaProducer.createImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", outputStream);
        byte[] imageBytes = outputStream.toByteArray();

        // 将图片转换为 Base64 编码
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        String imgUrl = "data:image/jpeg;base64," + base64Image;

        return ResultUtils.success(imgUrl);
    }
}